package com.dobby.okhttp.demo.jianshu;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import okhttp3.*;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 使用 okhttp
 * Created by jonas on 2017/2/10.
 */
public class JianshuPublisher {

    private OkHttpClient okHttpClient = new OkHttpClient();

    private String cookie = null;

    private JianshuPublisher() {
    }

    private JianshuPublisher(String cookie) {
        this.cookie = cookie;
    }


    public static JianshuPublisher addCookie(String cookie) {
        if(cookie == null || cookie.length() == 0) {
            return new JianshuPublisher();
        }
        return new JianshuPublisher(cookie);
    }

    private Map<String, String> addHeaders() throws Exception {
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Accept","application/json, text/javascript, */*; q=0.01");
        headers.put("Accept-Language","zh-CN,zh;q=0.8,en;q=0.6,zh-TW;q=0.4");
        headers.put("Connection","keep-alive");
        headers.put("Content-Type","application/json; charset=utf-8");
        headers.put("Host","www.jianshu.com");
        headers.put("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36");
        headers.put("X-Requested-With","XMLHttpRequest");
        if(null != this.cookie) {
            headers.put("cookie", this.cookie);
        } else {
            throw new Exception("缺少cookie信息");
        }
        return headers;
    }


    /**
     * 新建笔记
     * @return
     * @throws IOException
     */
    public String newNote() throws Exception {
        return newNote(null);
    }


    /**
     * 在一个笔记本里面新建一个笔记
     * @param notebookId  可传可不传，不传就取默认的第一个笔记本
     * @throws IOException
     */
    public String newNote(Integer notebookId) throws Exception {
        String url = "http://www.jianshu.com/writer/notes";
        JSONObject jsonObject = new JSONObject();
        if(notebookId == null) {
            notebookId = getDefaultNotebookId(getAllNotebooks());
        }
        jsonObject.put("notebook_id", notebookId);  // 指定某个笔记本
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonObject.toJSONString());
        Request request = new Request.Builder()
                .url(url)
                .headers(Headers.of(addHeaders()))
                .post(requestBody)
                .build();
        Response response = okHttpClient.newCall(request).execute();
        if(response.isSuccessful()) {
            String jsonInfo = response.body().string();
            System.out.println(jsonInfo);
            return jsonInfo;
        }
        return null;
    }


    public String updateNote(Integer noteId, String title, String content) throws Exception {
        String url = "http://www.jianshu.com/writer/notes/" + noteId;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("title", title);
        jsonObject.put("content", content);

        String noteInfo = getNoteInfo(noteId);
        Integer autosave_control = ((JSONObject) JSON.parse(noteInfo)).getInteger("autosave_control");
        jsonObject.put("autosave_control", autosave_control + 1);   // 版本号，每次修改都要比上一次数值大

        Request request = new Request.Builder()
                .headers(Headers.of(addHeaders()))
                .url(url)
                .put(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonObject.toJSONString()))
                .build();

        Response response = okHttpClient.newCall(request).execute();
        String jsonInfo = response.body().string();
        System.out.println(jsonInfo);
        return jsonInfo;
    }


    /**
     * 发布笔记
     * 新建笔记之后，发布出去
     * @throws IOException
     */
    public String publishNote(Integer noteId) throws Exception {
        String url = "http://www.jianshu.com/writer/notes/" + noteId + "/publicize";

        Request request = new Request.Builder()
                .headers(Headers.of(addHeaders()))
                .post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), ""))
                .url(url)
                .build();

        Response response = okHttpClient.newCall(request).execute();
        String jsonInfo = response.body().string();
        System.out.println("publish note =====> " + jsonInfo);
        return jsonInfo;
    }


    /**
     *  编译笔记
     *  修改笔记之后的编译更新，相当于重新发布
     * @param noteId
     * @throws IOException
     */
    public String compileNote(Integer noteId) throws Exception {
        String url = "http://www.jianshu.com/writer/notes/" + noteId + "/compile";

        Request request = new Request.Builder()
                .headers(Headers.of(addHeaders()))
                .post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), ""))
                .url(url)
                .build();

        Response response = okHttpClient.newCall(request).execute();
        String jsonInfo = response.body().string();

        System.out.println("compile note =====> " + jsonInfo);
        return jsonInfo;
    }



    /**
     * 新建一个笔记，然后添加内容，最后发布
     * @return
     */
    public String newNoteThenPublish(String title, String content) throws Exception {
        System.out.println("============================= 同步简书 新建笔记 ========================================");
        String noteInfo = newNote();
        Integer noteId = ((JSONObject) JSON.parse(noteInfo)).getInteger("id");
        updateNote(noteId, title, content);
        publishNote(noteId);
        return getNoteInfo(noteId);
    }


    /**
     * 修改一个笔记的内容，然后发布
     * @return
     */
    public String updateNoteThenCompile(Integer noteId, String title, String content) throws Exception {
        System.out.println("============================= 同步简书 修改笔记 ========================================");
        updateNote(noteId,title, content);
        compileNote(noteId);
        return getNoteInfo(noteId);
    }


    /**
     * 删除笔记
     * @throws Exception
     */
    public String deleteNote(Integer noteId) throws Exception {
        String url = "http://www.jianshu.com/writer/notes/" + noteId + "/soft_destroy";

        Request request = new Request.Builder()
                .headers(Headers.of(addHeaders()))
                .url(url)
                .post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), ""))
                .build();
        Response response = okHttpClient.newCall(request).execute();
        String jsonInfo = response.body().string();
        System.out.println(jsonInfo);
        System.out.println("delete note =====> " + jsonInfo);
        return jsonInfo;
    }




    /**
     * 获取笔记的信息
     * @param noteId
     * @return
     * @throws IOException
     */
    public String getNoteInfo(Integer noteId) throws Exception {
        String url = "http://www.jianshu.com/writer/notes/" + noteId;
        Request request = new Request.Builder()
                .headers(Headers.of(addHeaders()))
                .url(url)
                .put(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), ""))
                .build();
        Response response = okHttpClient.newCall(request).execute();
        String jsonInfo = response.body().string();
        JSONObject jsonObject = (JSONObject) JSON.parse(jsonInfo);
        String link = (String) jsonObject.get("slug");
        String accessUrl = "http://www.jianshu.com/p/" + link;
        jsonObject.put("accessUrl", accessUrl);
        String newNoteInfo = jsonObject.toJSONString();
        System.out.println("note info =====> " + newNoteInfo);
        return newNoteInfo;
    }



    /**
     * 获取默认的笔记本id
     * @return
     */
    private Integer getDefaultNotebookId(String notebooks) {
        JSONArray jsonArray = (JSONArray) JSON.parse(notebooks);
        if(null == jsonArray) {
            return null;
        }
        JSONObject jsonObject = (JSONObject) jsonArray.get(0);
        Integer notebookId = (Integer)jsonObject.get("id");
        return notebookId;
    }


    /**
     * 获取所有的笔记本信息
     * @return
     */
    public String getAllNotebooks() throws Exception {
        String url = "http://www.jianshu.com/writer/notebooks";
        Request request = new Request.Builder()
                        .url(url)
                        .headers(Headers.of(addHeaders()))
                        .build();
        Response response = okHttpClient.newCall(request).execute();
        if(response.isSuccessful()) {
            String jsonInfo = response.body().string();
            System.out.println(jsonInfo);
            return jsonInfo;
        } else {
            throw new IOException("请求发生错误");
        }
    }



    /**
     * 获取用户的信息
     * @return
     * @throws Exception
     */
    public String getUserInfo() throws Exception {
        String url = "http://www.jianshu.com/settings/basic";
        Request request = new Request.Builder()
                .url(url)
                .headers(Headers.of(addHeaders()))
                .build();
        Response response = okHttpClient.newCall(request).execute();
        if(response.isSuccessful()) {
            String responseInfo = response.body().string();
            System.out.println("================> 简书获取到的用户信息 ======================\n" + responseInfo);
            return responseInfo;
        }
        return null;
    }


    /**
     * 判断是否绑定手机
     * @return
     * @throws Exception
     */
    public boolean isBindMobile() throws Exception {
        String userInfo = getUserInfo();
        JSONObject jsonObject = (JSONObject) JSONArray.parse(userInfo);
        JSONObject data = (JSONObject) (jsonObject.get("data"));
        String mobile_number = (String) data.get("mobile_number");
        System.out.println("============================================> 简书获取到的用户手机号为：" + mobile_number);
        if(mobile_number == null || mobile_number.length() == 0) {
            return false;
        } else {
            return true;
        }
    }



    public String uploadFile(File file) throws Exception {
        String getToken = "http://www.jianshu.com/upload_images/token.json?filename=" + file.getName();  // get filename
        String uploadQiniu = "http://upload.qiniu.com";  // post  token key

        Request request = new Request.Builder()
                .headers(Headers.of(addHeaders()))
                .url(getToken)
                .build();
        Response response = okHttpClient.newCall(request).execute();
        String tokenJson = response.body().string();
        String token = ((JSONObject)JSONObject.parse(tokenJson)).getString("token");
        String key = ((JSONObject)JSONObject.parse(tokenJson)).getString("key");

        RequestBody uploadRequestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("token", token)
                .addFormDataPart("key", key)
                .addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("image/jpeg"), file))
                .build();
        Request uploadReq = new Request.Builder()
                .headers(Headers.of(addHeaders()))
                .url(uploadQiniu)
                .post(uploadRequestBody)
                .build();

        Response uploadResp = okHttpClient.newCall(uploadReq).execute();
        String uploadRespInfo = uploadResp.body().string();
        System.out.println(uploadRespInfo);
        return uploadRespInfo;
    }


}
